package jmu.edu.yjc.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import jmu.edu.yjc.Utils.BeanCopyUtil;
import jmu.edu.yjc.Utils.WebUtils;
import jmu.edu.yjc.config.CustomCellWriteHeightConfig;
import jmu.edu.yjc.config.CustomCellWriteWeightConfig;
import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.entity.Elderly;
import jmu.edu.yjc.domain.vo.elderly.ExcelElderlyVo;
import jmu.edu.yjc.enums.AppHttpCodeEnum;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author yjc
 * @date 2023/4/6 0:28
 */
@Service("exportService")
public class ExportService {
    public <O, V> void export(HttpServletResponse response, String excelName,
                              List<O> list, Class<V> classZZ) {
        try {
            //设置请求头
            WebUtils.setDownLoadHeader(excelName, response);
            SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
            //把数据写入到excel中
            EasyExcel.write(response.getOutputStream(), classZZ).sheet(sfd.format(new Date()))
                    .registerWriteHandler(new CustomCellWriteWeightConfig())
                    .registerWriteHandler(new CustomCellWriteHeightConfig())
                    .doWrite(list);
        } catch (Exception e) {
            //如果出现异常也要响应json数据
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }
}
